package cn.com.qjun.dmsoft;
import cn.com.qjun.dmsoft.utils.RuntimeUtils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinNT;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author sun
 **/
public class DmRegHandler {
    public interface Kernel32Ext extends Library {
        Kernel32Ext INSTANCE = Native.load("kernel32", Kernel32Ext.class);

        void SetProcessDEPPolicy(int z);

        void GetSystemInfo(WinNT.SYSTEM_INFO lpSystemInfo);
    }


    /**
     * jna 调用标准免注册dll
     */
    private interface DmReg extends Library {
        DmReg INSTANCE = Native.load("DmReg.dll", DmReg.class);
        /**
         * SetDllPathA  字符串(Ascii码表示插件所在的路径),整数(0表示STA，1表示MTA)
         */
        int SetDllPathA(String format, int args);
        /**
         * SetDllPathW  字符串(Unicode码表示插件所在的路径),整数(0表示STA，1表示MTA)
         */
        void SetDllPathW(String format, int args);
        /**
         * 破解后接口 SetDllPathA =》CBlnwyBm
         */
        int CBlnwyBm(String dllPath, int mode);
    }
    /**
     * 封装一个静态方法，方便调用
     */
    public static int exec() {
        return new DmRegHandler().handler();
    }
    public int handler() {
        //获取dm.dll的绝对路径。
        File dmDllFile = new File("D:/home/dll/temp/"+ RandomUtil.randomInt(1,999999999)+"/dm.dll");
        InputStream resourceAsStream = RuntimeUtils.class.getResourceAsStream("/win32-x86/dm.dll");
        FileUtil.copyFile(resourceAsStream,dmDllFile);
        Path dmDll = Paths.get(dmDllFile.getAbsolutePath());
        Console.log("大漠插件路径:{}", dmDllFile.getAbsolutePath());
        int result = DmReg.INSTANCE.CBlnwyBm(dmDll.toAbsolutePath().toString(), 1);
        Console.log("免注册调用结果：{}", result == 1 ? "成功" : "失败");
        return result;
    }
}